from flask import Flask, render_template, request, jsonify
import os
from datetime import datetime
from PIL import Image

app = Flask(__name__)

IMAGE_DIR = "D:/shixiwendang/tupian/static/images"

# def resize_image(image_path, size=(800, 800)):
#     with Image.open(image_path) as img:
#         img = img.resize(size, Image.ANTIALIAS)
#         img.save(image_path)

def get_image_pairs(image_dir):
    files = os.listdir(image_dir)
    prefix_dict = {}

    for file in files:
        if file.endswith((".png", ".jpg", ".jpeg")):
            parts = file.split("_")
            if len(parts) >= 2:
                prefix = parts[0]
                date_str = parts[1].split(".")[0]
                try:
                    date = datetime.strptime(date_str, "%Y%m%d")
                    if prefix not in prefix_dict:
                        prefix_dict[prefix] = []
                    prefix_dict[prefix].append((date, file))

                    image_path = os.path.join(image_dir, file)
                    #resize_image(image_path)
                except ValueError:
                    continue

    for prefix in prefix_dict:
        prefix_dict[prefix].sort(key=lambda x: x[0])

    image_pairs = {}
    for prefix in prefix_dict:
        if len(prefix_dict[prefix]) >= 2:
            image_pairs[prefix] = [
                prefix_dict[prefix][-2][1],
                prefix_dict[prefix][-1][1], 
            ]

    return image_pairs

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/get_images")
def get_images():
    image_pairs = get_image_pairs(IMAGE_DIR)
    return jsonify(image_pairs)

if __name__ == "__main__":
    app.run(debug=True)